/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： RefererInterceptor.java
 * Date：18-11-5 上午11:10
 * Author: guomw
 */

package com.guomw.report.web.config;

import com.alibaba.fastjson.JSON;
import com.guomw.report.common.config.Constant;
import com.guomw.report.common.enums.AppCode;
import com.guomw.report.common.utils.ApiResult;
import com.guomw.report.common.utils.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 利用referer请求头简单实现防盗链
 *
 * @author guomw
 * @date 2018/9/29
 */
public class RefererInterceptor implements HandlerInterceptor {
    @Autowired
    private Environment environment;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//        httpServletResponse.setContentType("application/json");
//        httpServletResponse.setCharacterEncoding("utf-8");
//        String s = httpServletRequest.getServletPath();
//        //获取referer配置
//        String referer = PropertyUtil.getProperty("referer", "");
//        if (!s.contains("verifyCode") && !StringUtils.isEmpty(referer)) {
//            // 获取请求是从哪里来的
//            String ref = httpServletRequest.getHeader("referer");
//            if (ref == null || !ref.startsWith(referer)) {
//                httpServletResponse.getWriter().write(JSON.toJSONString(ApiResult.resultWith(AppCode.NOT_AUTHORITY)));
//                return false;
//            }
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
